package org.gdstash.file;

import org.gdstash.util.GDMsgLogger;

import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class GDMappedByteBuffer extends GDAbstractBuffer {
    private File file;
    private RandomAccessFile raf;
    private MappedByteBuffer buffer;

    public GDMappedByteBuffer(final File file) {
        this.file = file;
        try {
            this.raf = new RandomAccessFile(file, "r");
            (this.buffer = this.raf.getChannel().map(FileChannel.MapMode.READ_ONLY, 0L, this.raf.length())).order(ByteOrder.LITTLE_ENDIAN);
        } catch (IOException ex) {
            GDMsgLogger.addError(ex);
            try {
                this.close();
            } catch (IOException ex2) {
            }
        }
    }

    @Override
    public byte[] getByteArray(final int length) throws IOException {
        final byte[] b = new byte[length];
        this.buffer.get(b);
        return b;
    }

    @Override
    public byte getByte() {
        return this.buffer.get();
    }

    @Override
    public int getInt() throws IOException {
        return this.buffer.getInt();
    }

    @Override
    public long getLong() throws IOException {
        return this.buffer.getLong();
    }

    @Override
    public short getShort() throws IOException {
        return this.buffer.getShort();
    }

    @Override
    public long getPosition() throws IOException {
        return this.buffer.position();
    }

    @Override
    public void setPosition(final long pos) throws IOException {
        if (pos > 2147483647L) {
            throw new EOFException();
        }
        this.buffer.position((int) pos);
    }

    @Override
    public void close() throws IOException {
        this.buffer = null;
        this.raf.close();
    }
}
